import axios from "axios";
import { Toast } from "antd-mobile";

const instance = axios.create({
  baseURL: import.meta.env.VITE_URL,
  timeout: 10000,
});

let count = 0;
instance.interceptors.request.use(
  (config) => {
    count++;
    if (count === 1) {
      Toast.show({
        icon: "loading",
        content: "加载中…",
        duration: 0,
      });
    }
    const token = localStorage.getItem("token");
    config.headers.Authorization = `Bearer ${token}`;
    return config;
  },
  function (error) {
    console.log(error);
  }
);

instance.interceptors.response.use(
  (config) => {
    count--;
    if (count === 0) {
      Toast.clear();
    }
    return config;
  },
  function (error) {
    count--;
    if (count === 0) {
      Toast.clear();
    }
    console.log(error);
  }
);

export default instance;
